package com.newsee.remote.ecommerce.commerce.colipu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newsee.remote.common.dto.ecommerce.colipu.TokenColDTO;
import com.newsee.remote.common.enumeration.EcommerceEnum;
import com.newsee.remote.common.utils.ecache.ConcurrentHashMapCacheUtil;
import com.newsee.remote.common.utils.http.HttpClientExecutor;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.common.utils.tools.EncryptUtil;
import com.newsee.remote.ecommerce.commerce.colipu.service.IColipuTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liangzhi.chen
 * @description 科力普token impl
 * @date 2019/7/18 下午 02:51
 **/
@Slf4j
@Service
public class ColipuTokenServiceImpl implements IColipuTokenService {

    /**
     * 用户名
     */
    @Value("${colipuUserName}")
    private String colipuUserName;

    /**
     * m密码
     */
    @Value("${colipuPassword}")
    private String colipuPassword;

    /**
     * 统一url
     */
    @Value("${colipuContextPath}")
    private String colipuContextPath;

    /**
     * 获取token方法名
     */
    @Value("${colipuGetTokenUrl}")
    private String colipuGetTokenUrl;

    /**
     * 获取token接口
     *
     * @return token
     */
    @Override
    public String getToken() {
        String token = StringUtils.EMPTY;
        Object o = ConcurrentHashMapCacheUtil.get(EcommerceEnum.E_COLIPU.getDesc());
        if (null != o) {
            token = o.toString();
            return token;
        }

        //获取科力普的token
        Map<String, String> params = new HashMap<>(2);
        String timestamp = DateUtils.format(new Date(), DateUtils.DATE_PATTERN_YMD);
        params.put("timestamp", timestamp);
        params.put("username", colipuUserName);
        //username+password+timestamp+password,将字符串MD5加密后的32位字符转为小写
        String password = colipuPassword;
        String sign = colipuUserName + password + timestamp + password;
        sign = EncryptUtil.encryptMd5(sign).toLowerCase();
        params.put("sign", sign);
        //调用接口获取

        try {
            //获取token的url
            String url = colipuContextPath + colipuGetTokenUrl;
            String response = HttpClientExecutor.doGet(url, params);
            JSONObject jsonReturn = JSON.parseObject(response);
            if (null != jsonReturn) {
                String resultStr = jsonReturn.getString("result");
                TokenColDTO tokenColDTO = JSON.parseObject(resultStr, TokenColDTO.class);
                //成功
                if (jsonReturn.getBoolean("success")) {
                    String accessToken = tokenColDTO.getAccess_token();
                    ConcurrentHashMapCacheUtil.put(EcommerceEnum.E_COLIPU.getDesc(), accessToken);
                    token = accessToken;
                } else {
                    log.error("error:requestId(" + jsonReturn.getString("requestId")
                            + ");errorcode(" + jsonReturn.getString("errorcode")
                            + ");errormsg(" + jsonReturn.getString("errormsg") + ")");
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return token;
    }
}
